//获取url中的参数
function getUrlParameters() {
    var urlParams = {};
    var match,
        regex = /([^&=]+)=([^&]*)/g;
    var searchString = window.location.search.substring(1);
    while ((match = regex.exec(searchString))) {
        var key = decodeURIComponent(match[1]);
        var value = decodeURIComponent(match[2]);
        urlParams[key] = value;
    }
    return urlParams;
}

//获取随机字符串
function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function downloadFile(url, download) {
    var a = document.createElement("a");
    var href = url;
    a.href = href;
    a.download = download;
    if (navigator.userAgent.startsWith("Mozilla")) {
        a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}))
    } else a.click();
}

function ab2str(u, f) {
    var b = new Blob([u]);
    var r = new FileReader();
    r.readAsText(b, 'utf-8');
    r.onload = function () {
        if (f) f.call(null, r.result)
    }
}

//null转空字符串
function NullToBlank(value) {
    if (value == undefined) return "";
    else return value;
}

//检查手机号
function checkMobile(mobile) {
    var reg = /^0?1[35789]{1}[0-9]\d{8}$/;
    return reg.test(mobile) ? true : false;
}

//求和
function getSum(data) {
    if (data.length == 0) return 0.0;
    return data.reduce(function (a, b) {
        return a + b;
    })
}

/**
 * 获取下一个编码 000001，000001000006，6
 * 得到结果 000001000007
 */
function getNextCode(prefix, maxCode, length) {
    if (maxCode == null) {
        var str = "";
        for (var i = 0; i < length - 1; i++) {
            str += "0";
        }
        return prefix + str + 1;
    } else {
        var str = "";
        var sno = parseInt(maxCode.substring(prefix.length)) + 1;
        for (var i = 0; i < length - sno.toString().length; i++) {
            str += "0";
        }
        return prefix + str + sno;
    }
}

function showTable(searchUrl,param, table,showCallback) {
    var search = function () {
        AsyncGet(searchUrl, param, function (value) {
            $(table).find("tbody").empty();
            for (var i = 0; i < value.length; i++) {
                var tr = $("<tr></tr>");
                $(table).find("thead th").each(function () {
                    if ($(this).find("input:checkbox").length > 0) {
                        var td = $("<td><input type='checkbox'></td>");
                        var checked = NullToBlank(value[i][$(this).attr("name")]);
                        if(checked == "1"){
                            $(td).find("input").prop("checked", true);
                        }
                        tr.append(td);
                    } else if ($.trim($(this).attr("name")) == "") {
                        var td = $("<td style='text-align: center;'>")
                        if(icons != null) {
                            icons.forEach(function (icon) {
                                td.append(getA(icon["icon"], icon["title"], icon["type"], icon["callback"]));
                            })
                        }
                        tr.append(td);
                    } else if ($(this).is(":hidden")) {
                        tr.append("<td style='display:none;'>" + NullToBlank(value[i][$(this).attr("name")]) + "</td>");
                    } else if ($(this).attr("input") != null) {
                        var inputType = $(this).attr("input");
                        var width = $(this).attr("width");
                        if(inputType == "a") {
                            var url = value[i][$(this).attr("target")];
                            var td = $("<td style='text-align: center;'><a target='_blank' href="+url+"></a></td>");
                            $(td).find("a").val(NullToBlank(value[i][$(this).attr("name")]));
                            if(width != null){
                                $(td).find("a").css("width",width);
                            }
                        }else{
                            var td = $("<td style='text-align: center;'><input type="+inputType+"></td>");
                            $(td).find("input").val(NullToBlank(value[i][$(this).attr("name")]));
                            if(width != null){
                                $(td).find("input").css("width",width);
                            }
                        }
                        tr.append(td);
                    } else {
                        if ($(this).attr("format") != null) {
                            var date = new Date(value[i][$(this).attr("name")] * 1000);
                            tr.append("<td style='text-align: center;'>" + date.Format($(this).attr("format")) + "</td>");
                        } else if ($(this).attr("href") != null) {
                            var path = value[i][$(this).attr("name")];
                            var type = $(this).attr("href");
                            var td = $("<td style='text-align: center;'></td>");
                            var cdnPath = NullToBlank(path).split(";")
                            cdnPath.forEach(function (s) {
                                if (s != null && s != "") {
                                    var a = $("<a>" + NullToBlank(s) + "</a>");
                                    if (type == "file") {
                                        a.click(function () {
                                            getFileDownload("/func/file/ajax", {path: path});
                                        }).css("cursor", "pointer")
                                    } else if (type == "cdn") {
                                        a.attr("target", "_blank").attr("href", s);
                                        td.append(a);
                                    } else {
                                        a.attr("target", "_blank").attr("href", "/func/image/html?path=" + s);
                                    }
                                    td.append(a);
                                    td.append("<br/>");
                                }
                            })
                            tr.append(td);
                        } else {
                            tr.append("<td style='text-align: center;'>" + NullToBlank(value[i][$(this).attr("name")]) + "</td>");
                        }
                    }
                })
                $(table).find("tbody").append(tr);
            }
            if (showCallback) showCallback()
        })
    }
    var selectAll = function () {
        if (table.find("thead tr th input:checkbox").length > 0) {
            table.find("thead tr th input:checkbox").change(function () {
                if ($(this).prop("checked") == true) {
                    table.find("tbody input:checkbox").prop("checked", true);
                } else {
                    table.find("tbody input:checkbox").prop("checked", false);
                }
            })
        }
    }

    search();
    selectAll();
    var object = new Object();
    object.search = search;
    return object;
}

/*
*param{
*
*  pageUrl          ,总页数url
*  searchUrl        ,查询数据的url
*  searchDiv        ,查询数据的容器
*  table            ,渲染数据的表格
*  pageSize         ,页面大小的容器
*  paging           ,分页的容器
*  icons:[{
*     "icon"        ,按钮
*     "title"       ,提示信息
*     "type"        ,按钮类型
*     "callback"    ,点击回调
*  }]
*  editIcon         ,编辑按钮
*  editTitle        ,编辑提示信息
*  deleteIcon       ,删除按钮
*  deleteTitle      ,删除提示信息
*  showCallback     ，页面渲染完成之后的回调
* }
**/
//根据url，参数data初始化table中的数据
function initTable(pageUrl, searchUrl, searchDiv, table, pageSize, paging, editIcon, editTitle, deleteIcon, deleteTitle, showCallback) {
    var icons;
    if(arguments.length==1){
        var objectparam=arguments[0]
        pageUrl=objectparam['pageUrl']
        searchUrl=objectparam['searchUrl']
        searchDiv=objectparam['searchDiv']
        table=objectparam['table']
        pageSize=objectparam['pageSize']
        paging=objectparam['paging']
        editIcon=objectparam['editIcon']
        editTitle=objectparam['editTitle']
        deleteIcon=objectparam['deleteIcon']
        deleteTitle=objectparam['deleteTitle']
        showCallback=objectparam['showCallback']
        icons=objectparam['icons']
    }
    editIcon = editIcon || 'fa fa-edit';
    editTitle = editTitle || '编辑';
    deleteIcon = deleteIcon || 'fa fa-trash-o';
    deleteTitle = deleteTitle || '删除';

    if (icons == null) {
        icons=new Array();
        icons.push({"icon":editIcon,"title":editTitle,type:"edit"});
        icons.push({"icon":deleteIcon,"title":deleteTitle,type:"delete"});
    }

    var object = new Object();
    var getDataBySearchId = function () {
        var param = {};
        $(searchDiv).find("input[name],select[name]").each(function (index, value) {
            param[$(this).attr("name")] = $(this).val();
        });
        param['size'] = pageSize.val() || pageSize.find(".page_active").text();
        return param;
    }
    var changeFunction = function () {
        $(searchDiv).find("input[name],select[name]").change(function () {
            $(paging).find("a.active").removeClass("active");
            search();
        })
        $(searchDiv).find("[data-btn-type='search']").click(function () {
            $(paging).find("a.active").removeClass("active");
            search();
        })
        pageSize.change(function () {
            $(paging).find("a.active").removeClass("active");
            search();
        })
    }

    var selectAll = function () {
        if (table.find("thead tr th input:checkbox").length > 0) {
            table.find("thead tr th input:checkbox").change(function () {
                if ($(this).prop("checked") == true) {
                    table.find("tbody input:checkbox").prop("checked", true);
                } else {
                    table.find("tbody input:checkbox").prop("checked", false);
                }
            })
        }
    }

    var getSelectData=function () {
        var array=table.find("tbody tr input:checkbox:checked").map(function(){
            return $(this).parents("tr").find("td:first").text();
        })
        return array.toArray();
    }

    var getA=function(icon,title,type,callback){
        var a=$("<a class='" + icon + "' title='" + title + "' style='cursor:pointer;margin: 0 10%;' type='"+type+"'></a>");
        a.data("clickCallback",callback);
        return a;
    }

    var search = function () {
        var param = getDataBySearchId();
        AsyncGet(pageUrl, param, function (totalPage) {
            $(table).find("tbody").empty();
            startPage(paging, totalPage, function (page) {
                if (totalPage == 0) return;
                param['page'] = page - 1;
                AsyncGet(searchUrl, param, function (value) {
                    $(table).find("tbody").empty();
                    for (var i = 0; i < value.length; i++) {
                        var tr = $("<tr></tr>");
                        $(table).find("thead th").each(function () {
                            if ($(this).find("input:checkbox").length > 0) {
                                tr.append("<td><input type='checkbox'></td>") ;
                            } else if ($.trim($(this).attr("name")) == "") {
                                var td=$("<td style='text-align: center;'>")
                                icons.forEach(function(icon){
                                    td.append(getA(icon["icon"],icon["title"],icon["type"],icon["callback"]));
                                })
                                tr.append(td);
                            } else if ($(this).is(":hidden")) {
                                tr.append("<td style='display:none;'>" + NullToBlank(value[i][$(this).attr("name")]) + "</td>");
                            } else if ($(this).attr("input") != null) {
                                var inputType = $(this).attr("input");
                                var width = $(this).attr("width");
                                if(inputType == "a") {
                                    var url = value[i][$(this).attr("target")];
                                    var td = $("<td style='text-align: center;'><a target='_blank' href="+url+"></a></td>");
                                    $(td).find("a").text(NullToBlank(value[i][$(this).attr("name")]));
                                    if(width != null){
                                        $(td).find("a").css("width",width);
                                    }
                                }else{
                                    var td = $("<td style='text-align: center;'><input type="+inputType+"></td>");
                                    $(td).find("input").val(NullToBlank(value[i][$(this).attr("name")]));
                                    if(width != null){
                                        $(td).find("input").css("width",width);
                                    }
                                }
                                tr.append(td);
                            } else {
                                if ($(this).attr("format") != null) {
                                    var date = new Date(value[i][$(this).attr("name")] * 1000);
                                    tr.append("<td style='text-align: center;'>" + date.Format($(this).attr("format")) + "</td>");
                                } else if ($(this).attr("href") != null) {
                                    var path = value[i][$(this).attr("name")];
                                    var type = $(this).attr("href");
                                    var td = $("<td style='text-align: center;'></td>");
                                    var cdnPath=NullToBlank(path).split(";")
                                    cdnPath.forEach(function(s){
                                        if(s!=null&&s!=""){
                                            var a = $("<a>" + NullToBlank(s) + "</a>");
                                            if (type == "file") {
                                                a.click(function () {
                                                    getFileDownload("/func/file/ajax", {path: path});
                                                }).css("cursor", "pointer")
                                            }else if(type == "cdn"){
                                                a.attr("target","_blank").attr("href",s );
                                                td.append(a);
                                            }else {
                                                a.attr("target","_blank").attr("href","/func/image/html?path=" + s );
                                            }
                                            td.append(a);
                                            td.append("<br/>");
                                        }
                                    })
                                    tr.append(td);
                                } else {
                                    tr.append("<td style='text-align: center;'>" + NullToBlank(value[i][$(this).attr("name")]) + "</td>");
                                }
                            }
                        })
                        $(table).find("tbody").append(tr);
                    }
                    if (showCallback) showCallback()
                })
            }, 5, modals.error);
        })
    }
    search();
    changeFunction();
    selectAll();
    object.search = search;
    object.getSelectData = getSelectData;
    return object;
}

/*
*param{
*
*  htmlUrl          ,实体的url
*  addHtmlUrl          ,实体的url
*  updateHtmlUrl          ,实体的url
*  updateEntityUrl  ,修改实体的url
*  updateBeforeCallback  ,修改实体之前的回调,
*  addEntityUrl     ,添加实体的url
*  addBeforeCallback  ,添加实体之前的回调,
*  deleteEntityUrl  ,删除的url
*  deleteId         ,删除的id参数
*  getEntityUrl     ,获取实体的url
*  getId            ,获取实体的id参数
*  getEntityBefore  ,获取实体之前
*  initFormDataCallback, 填充表单后的回调
*  initFormDataBeforeCallback , 填充表单前的回调
*  editTitle        ,编辑title
*  table            ,表格
*  addButton        ,添加按钮
*  addButtonCallback,添加界面显示之后的回调
*  addTitle         ,添加title
*  cancel_label     ,取消按钮
*  ok_label         ,确定按钮
*  hideFunc        ,窗口关闭之后的回调
*  addCallback  ,添加成功的回调
*  updateCallback  ,更新成功的回调
* }
* callback          ,操作成功的回调函数
**/
function EditEntity(param, callback) {
    var winId = param.winId ? param.winId : randomString();
    var clickId;
    var type = "update";
    if (param.htmlUrl || param.updateHtmlUrl || param.addHtmlUrl) {
        modals.openWin({
            winId: winId,
            url: param.htmlUrl ? param.htmlUrl : param.updateHtmlUrl ? param.updateHtmlUrl : param.addHtmlUrl,
            show: false,
            cancel_label: param.cancel_label,
            ok_label: param.ok_label,
        })
    }
    var modal = $("#" + winId);

    var showModals=function(showCallback){
        modals.showWin(winId);
        if(type == "update"){
            modal.find('.modal-title').text(param.editTitle);
            modal.find('[updateonlyread]').prop("disabled", true);
            modal.find('[addonlyread]').prop("disabled", false);
        }
        if(type == "add"){
            modal.find('.modal-title').text(param.addTitle);
            modal.find('[updateonlyread]').prop("disabled", false);
            modal.find('[addonlyread]').prop("disabled", true);
        }
        modal.find('[onlyread]').prop("disabled", true);
        if(param.showCallback){
            param.showCallback();
        }
        showCallback();
    }
    var updateCallback=function () {
        if (param.getEntityBefore) param.getEntityBefore();
        if (param.getEntityUrl != null) initFormData(param.getEntityUrl + "/" + clickId, null, modal.find(".modal-body form"),param.initFormDataCallback, param.initFormDataBeforeCallback);
    }
    var addCallback=function () {
        clearFormData(modal.find(".modal-body form"));
        if (param.addButtonCallback) param.addButtonCallback();
    }

    param.table.on("click", "tbody td a[type='delete']", function () {
        clickId = $(this).parents("tr").find("td:first").text();
        modals.confirm("确定删除吗?", function () {
            AsyncDelete(param.deleteEntityUrl + "/" + clickId, null, function (value) {
                modals.correct("删除成功", callback);
            })
        })
    })

    param.table.on("click", "tbody td a[type='edit']", function () {
        clickId = $(this).parents("tr").find("td:first").text();
        type = "update";
        if (param.updateHtmlUrl) {
            modal.find('.modal-body').load(param.updateHtmlUrl, function () {
                showModals(updateCallback);
            });
        } else {
            showModals(updateCallback);
        }
    })


    if(param.addHtmlUrl||param.htmlUrl){
        param.addButton.click(function () {
            type = "add";
            if (param.addHtmlUrl) {
                modal.find('.modal-body').load(param.addHtmlUrl, function () {
                    showModals(addCallback);
                });
            } else {
                showModals(addCallback);
            }
        })
    }

    param.table.on("click", "tbody td a", function () {
        clickId = $(this).parents("tr").find("td:first").text();
        var aCallback=$(this).data("clickCallback");
        if(aCallback) aCallback.call(this.parentNode.parentNode,clickId);
    })

    if (param.updateEntityUrl || param.addEntityUrl) {
        modal.find(".modal-footer button:last").show().unbind("click").click(function () {
            var form = getFormData(modal.find(".modal-body form"));
            if (type == "add") {
                if (param.addBeforeCallback) param.addBeforeCallback(form);
                AsyncPost(param.addEntityUrl, form, function (value) {
                    modals.hideWin(modal.attr("id"));
                    callback();
                    if(param.addCallback){
                        param.addCallback(value);
                    }
                })
            }
            if (type == "update") {
                append(form, {id: clickId});
                if (param.updateBeforeCallback) form = param.updateBeforeCallback(form);
                AsyncPut(param.updateEntityUrl, form, function (value) {
                    modals.hideWin(modal.attr("id"));
                    callback();
                    if(param.updateCallback){
                        param.updateCallback(value);
                    }
                })
            }
        })
    } else {
        modal.find(".modal-footer button:last").hide();
    }

    modal.find(".modal-footer button:first").show().unbind("click").click(function () {
        var form = getFormData(modal.find(".modal-body form"));
        if (type == "update") append(form, {id: clickId});
        if(param.hideFunc) param.hideFunc(form);
    })
    return winId;
}

